<?php

/**
 * @author Wrzasq <wrzasq@gmail.com>
 * @copyright 2009 (C) by Wrzasq.
 * @version 0.0.1
 * @since 0.0.1
 * @package WrzasqCMF
 */

class Site extends Base_Record
{
    static protected $validate = array(
      'gaLogin' => array(RECORD_INTERNAL,'allowEmpty','googleLogin'),
      'gaPassword' => array(RECORD_INTERNAL,'allowEmpty','googlePassword'),
      'gaId' => array(RECORD_INTERNAL,'allowEmpty','googleAnalyticsId'),
      'name' => array('notEmpty','plainText'),
      'hostname' => array('notEmpty','hostname'),
      'asLogin' => array('allowEmpty','googleLogin'),
      'asPassword' => array('allowEmpty','googlePassword'),
      'findTweets' => array('allowEmpty','positiveInteger'),
      'emailReport' => array(RECORD_INTERNAL,'allowEmpty','email'),
      'emailReportFreq' => array(RECORD_INTERNAL,'allowEmpty','positiveInteger'),
      );
    static protected $names = array(
      'gaLogin' => 'Google Analytics Login',
      'gaPassword' => 'Google Analytics Password',
      'gaId' => 'Google Analytics ID',
      'name' => 'Short name',
      'hostname' => 'Domain',
      'asLogin' => 'Google AdSense login',
      'asPassword' => 'Google AdSense password',
      'findTweets' => 'Find Tweets',
      'emailReport' => 'E-mail',
      'emailReportFreq' => 'Frequency'
      );
    static protected $descriptions = array(
      'gaLogin' => 'Login to the Google Analytics account with access to the site',
      'gaPassword' => 'Password to the Google Analytics',
      'gaId' => 'Page ID in Google Analytics',
      'name' => 'Short name of the site used in searches',
      'hostname' => 'Just a domain, without protocol, slashes, etc.',
      'asLogin' => 'Google AdSense login',
      'asPassword' => 'Google AdSense password',
      'findTweets' => 'Find and store given amount of Twitter entries daily',
      'emailReport' => 'E-mail for sending reports',
      'emailReportFreq' => 'Frequency in days'
      );
    static protected $validationErrors = array(
      'googleAnalytics' => 'You have to fill login, password and ID to work with Google Analytics',
      'googleAnalyticsAuth' => 'Failed to authenticate user with given data ',
      'googleAdSense' => 'You have to fill both login and password to work with Google AdSense',
      'emailReport' => 'You have to fill both e-mail and frequency value to enable reporting'
      );
  
    /**
     * @var int
     */
    protected $idAccount;

    /**
     * @var Account
     */
    protected $account;        
    
    static public function getVarName( $key )
    {
      return isset(self::$names[$key]) ? self::$names[$key] : null;
    }
    
    static public function getVarDescription( $key )
    {
      return isset(self::$descriptions[$key]) ? self::$descriptions[$key] : null;
    }    
    
    protected function validateGroupFill( $key, $keys, $errorMsg )
    {
      //$asKeys = array('asLogin','asPassword');
      //if( in_array($key,$asKeys) ) {
        $filling = false;
        $empty = false;
        foreach( $keys as $asKey ) {
          if( $key !== $keys && !empty($this->$asKey) ) {
            $filling = true;            
          } else {
            $empty = true;
          }
        }
        if( $filling && $empty ) {
          return $errorMsg;
        }
      //}      
    }
    
    protected function internalValidation( $key )
    {           
      $asKeys = array('asLogin','asPassword');
      if( in_array($key,$asKeys) ) {
        $filling = false;
        $empty = false;
        foreach( $asKeys as $asKey ) {
          if( !empty($this->$asKey) ) {
            $filling = true;            
          } else {
            $empty = true;
          }
        }
        if( $filling && $empty && empty($this->$key) ) {
          return self::$validationErrors['googleAdSense'];
        }
      }
      $gaKeys = array('gaLogin','gaPassword','gaId');
      if( in_array($key,$gaKeys) ) {
        $filling = false;
        $empty = false;
        foreach( $gaKeys as $gaKey ) {
          if( !empty($this->$gaKey) ) {
            $filling = true;
          } else {
            $empty = true;
          }
        }
        if( $filling && $empty && empty($this->$key) ) {
          return self::$validationErrors['googleAnalytics'];
        }
      }
       
      $repKeys = array('emailReport','emailReportFreq');
      if( in_array($key,$repKeys) ) {
        $filling = false;
        $empty = false;
        foreach( $repKeys as $repKey ) {
          if( !empty($this->$repKey) ) {
            $filling = true;
          } else {
            $empty = true;
          }
        }
        if( $filling && $empty && empty($this->$key) ) {
          return self::$validationErrors['emailReport'];
        }
      }      
      return true;
    }
    
    public function validateAuthData()
    {
      try {
        if( !$this->gaLogin || !$this->gaPassword ) {
          return null;//throw new Exception('No data for Google Analytics');
        }
        $gapi = new Gapi($this->gaLogin,$this->gaPassword);          
      } catch( Exception $e ) {
        return array('googleAnalytics' => self::$validationErrors['googleAnalytics'] );
      }      
      return true;
    }
    
    public function hasValidGoogleAnalyticsAuth()
    {
      $errors = $this->validateAuthData();
      if( $errors === null ) {
        return null;
      }
      if( isset($errors['googleAnalytics']) ) {
        return false;
      }
      return true;
    }
    
    protected function &getValidationScheme()
    {
      return self::$validate;
    }
    
    /**
     * @return Account
     * @version 0.0.1
     * @since 0.0.1
     */
    public function getAccount()
    {
        if( !isset($this->account) )
        {
            $this->account = new Account();
            $this->account->load($this->idAccount);
        }

        return $this->account;
    }

    /**
     * @param Account $account
     * @version 0.0.1
     * @since 0.0.1
     */
    public function setAccount(Account $account)
    {
        $this->account = $account;
        $this->idAccount = $account->getID();
    }

    /**
     * @param int $id
     * @return Site
     * @version 0.0.1
     * @since 0.0.1
     */
    public function load($id)
    {
        $this->_import('sites',array('idSite'=>$id));
        return $this;
    }
    
    public function isLoaded()
    {
      return isset($this->idSite);
    }
    
    public function getID()
    {
      return $this->idSite;
    }

    /**
     * @param Account $account
     * @param string $name
     * @return Site
     * @version 0.0.1
     * @since 0.0.1
     */
    public function loadByAccountAndName(Account $account, $name)
    {
        $query = $this->database->prepare('SELECT `idSite`, `idAccount`, `name` FROM `sites` WHERE `idAccount` = :account AND `name` = :name');
        $query->bindValue(':account', $account->getID(), PDO::PARAM_INT);
        $query->bindParam(':name', $name, PDO::PARAM_STR);
        $query->bindColumn('idSite', $this->id, PDO::PARAM_INT);
        $query->bindColumn('idAccount', $this->idAccount, PDO::PARAM_INT);
        $query->bindColumn('name', $this->name, PDO::PARAM_STR);
        $query->execute();
        $query->fetch();

        return $this;
    }
    
    protected function getModelVars()
    {
      $vars = parent::getModelVars();
      $vars['idAccount'] = $this->getAccount()->getID();
      return $vars;
    }

    /**
     * @return Account
     * @version 0.0.1
     * @since 0.0.1
     */
    public function save()
    {
      if( $this->validate() === false ) {
        throw new Base_RecordException('Cannot save invalid data');
      }
      $vars = $this->getModelVars();
      var_dump($vars);
      $id = isset($vars['idSite']) ? $vars['idSite'] : null;
      unset($vars['idSite']);
      if( $id ) {
        $this->_update('sites',$vars,array('idSite'=>$id));
      } else {
        $this->_insert('sites',$vars);
        $this->id = $this->database->lastInsertId();
      }
      return $this;
    }
    
    /**
     * @return Site
     * @version 0.0.1
     * @since 0.0.1
     */
    public function delete()
    {
        $query = $this->database->prepare('DELETE FROM `sites` WHERE `idSite` = :id');
        $query->bindParam(':id', $this->id, PDO::PARAM_INT);
        $query->execute();
        $query = $this->database->prepare('DELETE FROM `sites_data` WHERE `idSite` = :id');
        $query->bindParam(':id', $this->id, PDO::PARAM_INT);
        $query->execute();        
        unset($this->id);
        return $this;
    }
}